<template>
    <el-form ref="ruleForm" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="描述" prop="describe">
            <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="分类" :gutter="20">
            <el-col :span="6">
                <el-select v-model="form.cate_1st" @change="handleCateChange" placeholder="please select your zone"
                    prop="classify1">
                    <el-option v-for="item in option_1st" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-col>
            <el-col :span="6">
                <el-select v-model="form.cate_2nd" prop="classify2">
                    <el-option v-for="item in option_2nd" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-col>
        </el-form-item>
        <el-form-item label="图片">
            <el-upload class="avatar-uploader" action="http://localhost:3001/upload/common/" :show-file-list="false"
                :headers="headers" accept=".jpeg,.png,.jpg" :data="extra" :on-success="handleAvatarSuccess"
                :on-error="handleUploadError" :before-upload="handleBeforeUpload">
                <img v-if="form.main_photo" :src="form.main_photo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="cotent">
            <div style="border: 1px solid #ccc">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                    :mode="mode" />
                <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
                    :mode="mode" @onCreated="handleCreated" />
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit(ruleForm)">保存修改</el-button>
        </el-form-item>
    </el-form>
</template>
  
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import aritcle from '@/api/aritcle';
import category from '@/api/cate';
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive, watchEffect, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRoute, useRouter } from 'vue-router';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
let mode = ref('simple');
// 内容 HTML
const valueHtml = ref('')
//配置
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...', MENU_CONF: {} }
//上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',
    server: 'http://localhost:3001/upload/editor/',
    //自定义http header
    headers: {
        Authorization: `Bearer ${sessionStorage.token}`,
    }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 添加token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
// 附加参数
let extra = { type: 'common' };
// 上传成功
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //如果上传成功
    if (status) {
        // 生成图片的地址
        form.value.main_photo = src;
        // form.avatar = URL.createObjectURL(uploadFile.raw);
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
// 上传失败
let handleUploadError = (error, uploadFile) => {
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);
}
const handleBeforeUpload = (rawFile) => {
    // 判断图片格式/^imge\/(jpeg|png|jpg)$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!')
        return false
    }
    //图片大于2MB
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像体积不能大于2MB!')
        return false
    }
    return true
}

let route = useRoute();
// 获取实例
let form = ref({
    title: '',
    description: '',
    cate_1st: '',
    cate_2nd: '',
    main_photo: '',
    content: '',
});
// 校验
let ruleForm = ref();
// 请求子级
let loadInfo = async (id) => {
    let { status, data } = await category.list({ id });
    if (status) {
        return data;
    }
};

//一级分类
let option_1st = ref([]);

//二级分类
let option_2nd = ref([]);

let handleCateChange = async (value) => {
    // 请求二级分类
    option_2nd.value = await loadInfo(value);
    //默认选中二级分类的第一项
    form.value.cate_2nd = option_2nd.value[0].id
}
//初始化自动执行，自行分析数据，监听依赖变化
watchEffect(async () => {
    try {
        //1,请求一级分类
        option_1st.value = await loadInfo(0);
        //2,文章详情
        let { status, msg, data } = await aritcle.detail({ id: route.params.id });
        // console.log({ ...form.value }.cate_1st);
        //3,加载二级分类
        option_2nd.value = await loadInfo(data.cate_1st);
        form.value = data;
    } catch (error) {
        // console.log(error);
    }
})

const rules = reactive({
    title: [ // 为空执行上行，输入执行下行
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 3, message: '标题不得少于三个字', trigger: 'blur' },
    ],
    classify1: [{ required: true, }],
    classify2: [{ required: true, }],
    photo: '',
    content: [ // 为空执行上行，输入执行下行
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 10, message: '描述不得少于十个字', trigger: 'blur' },
    ],
})
// 确认提交
const onSubmit = (ruleForm) => {
    ruleForm.validate(async (valid, fields) => {
        if (valid) {
            //通过校验
            let { status, msg } = await aritcle.edit({ ...form.value });
            if (status) {
                location.assign('#/aritcle/list');
            } else {
                ElMessage.error(msg);
            }
        } else {
            //没通过校验
            console.log('校验失败字段', fields);
        }

    })
}
</script>
<style scoped>
.card-header {
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>